<template>
	<div ref="echartsRef" :style="echartsStyles"></div>
</template>

<script setup lang="ts" name="Echarts">
import { onMounted, ref, computed, watch, nextTick } from 'vue'
import { ECharts, EChartsOption } from 'echarts'
import { useEcharts } from '@/hooks/useEcharts'

type EventType = { [key: string]: any }

interface EchartProps {
	option: EChartsOption // 图表的选项值
	height?: string // 高度
	width?: string // 宽度
	events?: EventType // 图表的事件
}

const props = withDefaults(defineProps<EchartProps>(), {
	option: undefined,
	height: '200px',
	width: '100%',
	events: () => ({})
})

const echartsRef = ref<HTMLElement>()
let myChart: ECharts
const echartsStyles = computed(() => {
	return {
		height: props.height,
		width: props.width
	}
})

// 宽高变化出发图表重新resize
watch([() => props.height, () => props.width], () => {
	nextTick(() => {
		myChart && myChart.resize()
	})
})

// 选项变化自动更新图表
watch(
	() => props.option,
	val => {
		myChart && myChart.setOption(val)
	}
)

// 事件动态绑定
watch(
	() => props.events,
	(newVal, oldVal) => {
		if (oldVal) {
			initEvents(oldVal, 'off')
		}
		if (newVal) {
			initEvents(newVal, 'on')
		}
	}
)

// 初始化图表实例
const initInstance = (chart: ECharts) => {
	myChart = chart
}
// 获取图表实例
const getInstance = () => {
	return myChart
}

// 初始化图表鼠标事件
const initEvents = (events: EventType, optType: 'on' | 'off') => {
	if (events) {
		Object.keys(events).forEach(eventName => {
			myChart[optType](eventName, props.events[eventName])
		})
	}
}

onMounted(() => {
	const { chart } = useEcharts(echartsRef, props.option)
	initInstance(chart)
	initEvents(props.events, 'on')
})
defineExpose({
	getInstance
})
</script>
